package com.song.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.Reader;

/**
 * @Author 宋伟宁
 * @Date 2023/9/1
 * @Version 1.0
 **/
public class MybatisUtil {
    //SqlSessionFactory:工厂模式创建Sqlsesion
    private static SqlSessionFactory FACTORY;
    //ThreadLocal: 线程的安全的（解决线程不安全的问题）
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();

    private static final Logger logger= LoggerFactory.getLogger(MybatisUtil.class);
    static {
        try {
            //读取mybatis的核心配置文件：mybatis-config.xml
            Reader resource = Resources.getResourceAsReader("mybatis-config.xml");
            //创建SqlSessionFactory
            FACTORY = new SqlSessionFactoryBuilder().build(resource);

        } catch (IOException e) {
           logger.debug("未能获取mybatis-config.xml");
        }
    }

    /**
     * 返回SqlSessionFactory
     * @return
     */
    public  static SqlSessionFactory getFACTORY(){
        return  FACTORY;
    }

    /**
     * 创建SqlSession
     * @return
     */
    public static SqlSession getSqlSession(){
          //从ThreadLocal中获取SqlSession
          SqlSession sqlSession = threadLocal.get();
          if(sqlSession == null){
               //通过Factory创建SqlSession
               sqlSession=FACTORY.openSession();
               //加载到ThreadLocal中
              threadLocal.set(sqlSession);
          }
          return  sqlSession;
    }

    /**
     * 提交事务并关闭SqlSession
     */
    public static void closeSession() {
         SqlSession sqlSession = threadLocal.get();
         if(sqlSession != null){
             //提交事务
             sqlSession.commit();
             //关闭sqlSession
             sqlSession.close();
         }
         threadLocal.set(null);
    }

}
